package com.yunlongn.async.runnable;

import com.yunlongn.async.function.RetryScheduleAction;
import com.yunlongn.async.function.RetryScheduleFail;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 重试线程
 * @author yunlongn
 */
public class RetryRunnable<T> implements Callable<Boolean> {

    private final RetryScheduleAction<T> action;
    private int[] periods;
    private AtomicInteger index = new AtomicInteger(0);
    private TimeUnit timeUnit;

    public RetryRunnable(RetryScheduleAction<T> action,
                         TimeUnit timeUnit, int... periods) {
        this.action = action;
        this.periods = periods;
        this.timeUnit = timeUnit;
    }

    /**
     * 判断是否还有下一个执行时间
     */
    public boolean hashNext() {
        return index.incrementAndGet() <= periods.length;
    }

    public int next() {
        return periods[index.get() - 1];
    }

    @Override
    public Boolean call() {
        try {
            return action.execute(action.getParam());
        } catch (Throwable ignored) {
            return false;
        }
    }

    public RetryScheduleAction<T> getAction() {
        return action;
    }

    public int[] getPeriods() {
        return periods;
    }

    public void setPeriods(int[] periods) {
        this.periods = periods;
    }

    public AtomicInteger getIndex() {
        return index;
    }

    public void setIndex(AtomicInteger index) {
        this.index = index;
    }

    public TimeUnit getTimeUnit() {
        return timeUnit;
    }

    public void setTimeUnit(TimeUnit timeUnit) {
        this.timeUnit = timeUnit;
    }
}
